package com.zx.jhpt.service;

import com.zx.framework.core.exception.ServiceException;
import com.zx.framework.core.util.SpringBeanUtil;
import com.zx.framework.core.util.StringUtil;
import com.zx.framework.db.IBaseDAO;
import com.zx.jhpt.excel.vo.ImportColumn;
import com.zx.jhpt.excel.vo.Risk;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("dynamicService")
@Transactional(transactionManager="jsTransactionManager")
public class DynamicService {
	
	private static final Logger LOGGER = Logger.getLogger(DynamicService.class);
	/**
	 * 根据risk的设置传输表数据
	 * @param risk
	 */
	public void  dataTransfer(Risk risk,List<Map<String,Object>> datas,String cycle){
		if(StringUtil.isEmpty(risk.getTargetDao())){
			throw new ServiceException("数据传输的目标数据库设置[targetDao]不存在，请检查!");
		}
		if(StringUtil.isEmpty(risk.getTargetTbName())){
			throw new ServiceException("数据传输的目标数据库设置[targetTbName]不存在，请检查!");
		}
		if(risk.getIcolumns().size()==0){
			throw new ServiceException("数据传输的目标数据库设置[icolumns]不存在，请检查!");
		}
		IBaseDAO dao = SpringBeanUtil.getBean(risk.getTargetDao(),IBaseDAO.class);
		// 删除数据的依据条件 删除风险ID,周期对应数据
        // 获取定义里风险ID及周期的对应数据集市字段
        String fxidColumn = null,cycleColumn = null;
        for (ImportColumn column : risk.getIcolumns()) {
            if("fxid".equals(column.getSource())){
                fxidColumn = column.getTarget();
            }
            if("cycle".equals(column.getSource())){
                cycleColumn = column.getTarget();
            }
        }
        if(StringUtil.isBlank(fxidColumn)){
            throw new ServiceException("数据传输的目标数据库表[fxid]目标列未设置，请检查!");
        }
        if(StringUtil.isBlank(cycleColumn)){
            throw new ServiceException("数据传输的目标数据库表[cycle]目标列未设置，请检查!");
        }
		String sql = "delete from" + risk.getTargetTbName() + " where 1=1 " +
                " and " +fxidColumn + "=? " +
                " and " +cycleColumn + "=? ";
		dao.executeSQL(sql,risk.getFxid(),cycle);
		//整理插入语句
		sql = "insert into " + risk.getTargetTbName() ;
		sql += " (";
		StringBuilder sb = new StringBuilder();
		StringBuilder sb1 = new StringBuilder();
		List<String> cls = new ArrayList<String>();
		for (ImportColumn column : risk.getIcolumns()) {
			sb.append(column.getTarget()+",");
			sb1.append("?,");
			cls.add(column.getSource());
		}
		sql += sb.subSequence(0, sb.length()-1);
		sql += ") values (";
		sql += sb1.substring(0, sb1.length()-1);
		sql += ") ";
		//处理插入数据
		for (Map<String,Object> o : datas) {
			List<Object> params = new ArrayList<Object>();
			for (String c : cls) {
				params.add(o.get(c.toUpperCase()));
			}
			dao.executeSQL(sql, params.toArray());
		}
	}
}
